#include "Server.hpp"
#include "EventLoop.hpp"
#include <signal.h>
#include <memory>
#include <iostream> // 用于输出错误信息
#include <cstdlib>  // 用于 std::atoi

std::shared_ptr<Server> server;
void handle_signal(int) {
    server->stop_loop();
}



int main(int argc, char* argv[]) {
    signal(SIGINT, handle_signal);  // 处理Ctrl+C
    signal(SIGPIPE, SIG_IGN);       // 忽略SIGPIPE

    
    // 默认线程数
    int thread_count = 4;

    // 检查命令行参数
    if (argc > 1) {
        thread_count = std::atoi(argv[1]); // 将第一个参数转换为整数
        if (thread_count <= 0 || thread_count > 16) { // 限制线程数范围
            std::cerr << "Invalid thread count, range: [1, 16]. Using default value: 4" << std::endl;
            thread_count = 4;
        }
    }

    std::cout << "Starting server with " << thread_count << " threads..." << std::endl;

    // 创建服务器实例（动态线程数，监听8080端口）
    auto local_server = std::make_shared<Server>(thread_count, 8080);
    server = local_server;

    // 启动服务器
    server->start_loop();

    LOG << "Server stopped";
    server->stop_loop(); // 停止主事件循环
    std::cout << "Server stopped" << std::endl;

    return 0;
}